package com.md.application.service.users;


import com.md.api.authentication.MacApi;
import com.md.domain.model.po.Apis;
import com.md.model.system.CommonResult;
import com.md.repository.ApiRepository;
import com.md.repository.RoleApiRepository;
import com.md.repository.UsersRepository;
import com.md.util.ObjectUtil;
import com.md.value.constants.RedisCacheConstants;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

/**
 * @author 刘骄阳
 * 2022-04-01 18:30
 */
@Service
@RequiredArgsConstructor
public class MacApplicationService implements MacApi {
  private final UsersRepository usersRepository;
  private final ApiRepository apiRepository;
  private final RoleApiRepository roleApiRepository;

  /**
   * 查询用户信息
   *
   * @param id 主键id
   * @return 操作结果
   */
  @Override
  @Cacheable(value = RedisCacheConstants.MAC_USER_INFO, key = "#id")
  public CommonResult<Users> queryUsersInfo(final Long id) {
    // 此处应该构建响应实体
    return CommonResult.success(usersRepository.selectById(id));
  }

  /**
   * 查询接口信息
   *
   * @param url 接口路径
   * @return 接口信息
   */
  @Override
  @Cacheable(value = RedisCacheConstants.MAC_API, key = "#url")
  public CommonResult<Apis> queryApiInfo(final String url) {
    return CommonResult.success(apiRepository.queryApiByUrl(url));
  }

  /**
   * 查询是否有权限
   *
   * @param apiId  apiId
   * @param roleId 角色Id
   * @return 是否有权限
   */
  @Override
  @Cacheable(value = RedisCacheConstants.MAC_USER_ROLE, key = "#apiId+'_'+#roleId")
  public CommonResult<Boolean> queryHasAuth(final Long apiId, final Long roleId) {
    return CommonResult.success(ObjectUtil.notEmpty(roleApiRepository.queryByRoleIdOrApiId(apiId, roleId)));
  }
}
